//
//  CWJavaScriptApiDB.m
//  CWDevelop
//
//  Created by LittoCats on 7/10/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "CWJavaScriptApiDatabase.h"

#import "CWDataBase.h"

#define CWDATABASE action[@"__DATABASE"]

#define CBLQUERYRUNASYNCBLOCK ^(CBLQueryEnumerator *enumera, NSError *error)
@implementation CWJavaScriptApiDatabase

+ (void)analyseAction:(NSMutableDictionary *)action
{
    if (!action[@"db"] || [action[@"db"] isEmpty]) {
        CWLog(@"DB waring : database is not appointed , use default database< %@ >",[[NSBundle mainBundle] bundleIdentifier]);
        [action setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@""];
    }
    [action setObject:[CWDataBase dataBase:action[@"db"]] forKey:@"__DATABASE"];
}

#pragma mark
CWJavascriptApi(query)
{
    CWScriptFunction *function = [CWScriptFunction functionWithFunctionScript:params[@"filter"][@"___function"] context:CWJSCONTEXT];
    CBLQuery *query = [CWDATABASE slowQueryWithMap:^(NSDictionary *doc, CBLMapEmitBlock emit) {
        id key = [function evaluateWithArguments:doc, nil];
        emit(key,doc);
    }];
    query.descending = ![params[@"ascend"] boolValue];
    query.limit = [params[@"limit"] integerValue];
    query.skip = [params[@"skip"] integerValue];
    [query runAsync:CBLQUERYRUNASYNCBLOCK {
        NSMutableArray *result = [NSMutableArray new];
        for (CBLQueryRow *row in enumera) {
            [result addObject:row.documentID];
        }
    }];
}
@end
